/*

Copyright (c) 2008, Dependable Systems Lab, EPFL
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Dependable Systems Lab, EPFL nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

package conferr.gui;

import conferr.*;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.xml.transform.TransformerException;
import org.jdom.Document;

public class TestScenarioDialog extends javax.swing.JDialog {
    
    private Document doc;
    private FaultScenarioSet scenario;
    private HashMap<String, Document> configs;
    private HashMap<String, ConfigurationFile> configsObjs;
    private ErrorGenerator sset;
    
    /** Creates new form TestScenarioDialog */
    public TestScenarioDialog(java.awt.Frame parent, boolean modal, FaultInjectionPlan plan, FaultScenarioSet scenario, ErrorGenerator set) throws FileNotFoundException, ImpossibleConfigurationException, TransformerException {
        super(parent, modal);
        this.faultInjectionPlan1 = plan;
        
        this.configs = new HashMap<String, Document>();
        this.configsObjs = new HashMap<String, ConfigurationFile>();

        this.sset = set;               
        
        for (ConfigurationFile file : faultInjectionPlan1.getConfigurationFiles()) {
            
            ConfigurationTransform c = set.getConfigurationTransform(file);

            Transform f = c.getTransformInstance();

            if (f != null) {
                configs.put(file.getName(), f.filter(file.getDocument(), c ));
            } else {
                configs.put(file.getName(), file.getDocument());
            }
            configsObjs.put(file.getName(), file);
            if (configs.get(file.getName()) == null) {
                    JOptionPane.showMessageDialog(this, "Unable to parse " + file.getName());
                    return;
            }


        }
        
        initComponents();
        
        if (scenario.getFaultTemplateInstance() == null) {
            sizeLabel.setText("Unable to load action for the scenario");
            return;
        }
        
        maxFaults = scenario.getFaultTemplateInstance().getDescription(configs, scenario).numberOfFaults();

        if (maxFaults == -1) {
            sizeLabel.setText("The number of faults of this scenario cannot be evaluated");
        } else {
            sizeLabel.setText("This scenario contains " + maxFaults + " faults");
        } 
               
        it = scenario.getFaultTemplateInstance().faults(configs, new Random().nextLong(), scenario);
        count = 0;
        this.scenario = scenario;
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        faultInjectionPlan1 = faultInjectionPlan1;
        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        xmlOutput = new javax.swing.JRadioButton();
        nativeOutput = new javax.swing.JRadioButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        sizeLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jEditorPane1 = new javax.swing.JEditorPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jLabel3.setText("Output format:");
        jPanel1.add(jLabel3);

        buttonGroup1.add(xmlOutput);
        xmlOutput.setSelected(true);
        xmlOutput.setText("XML");
        jPanel1.add(xmlOutput);

        buttonGroup1.add(nativeOutput);
        nativeOutput.setText("Native");
        jPanel1.add(nativeOutput);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jPanel1, gridBagConstraints);

        jButton2.setText("Close");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jButton2, gridBagConstraints);

        jLabel2.setText("Difference with the original files:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jLabel2, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(sizeLabel, gridBagConstraints);

        jButton1.setText("Show next");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jButton1, gridBagConstraints);

        jScrollPane1.setPreferredSize(new java.awt.Dimension(300, 300));

        jEditorPane1.setContentType("text/html");
        jEditorPane1.setEditable(false);
        jScrollPane1.setViewportView(jEditorPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private long maxFaults;
    
    private Enumeration<FaultScenario> it = null;
    private long count = 0;
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
           this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        if (it != null) {
            if (!it.hasMoreElements()) {
                it = scenario.getFaultTemplateInstance().faults(configs, new Random().nextLong(), scenario);
                count = 0;
            }
            
            if (it.hasMoreElements()) {
                
                FaultScenario f = it.nextElement();
                
                Map<String, Document> modified = f.getDocument();                            
                
                String outputText = "<html>";                                
                
                for (Map.Entry<String, Document> entry : modified.entrySet()) {

                        ConfigurationFile file = configsObjs.get(entry.getKey());

                        ConfigurationTransform ct =  sset.getConfigurationTransform(file);
                        Transform f2 = ct.getTransformInstance();                                                
                        
                        outputText += "<b>" + file.getName() + "</b>";
                        
                        try {        
                            
                            Document unfilteredDoc;
                            
                            if (f2 != null) unfilteredDoc = f2.unfilter(entry.getValue(), ct);
                            else unfilteredDoc = entry.getValue();
                            
                            
                            String diff;
                            
                            if (xmlOutput.isSelected()) {
                                diff = ConfigurationDiff.getXmlDiff(file.getDocument(), unfilteredDoc);
                            } else {
                                diff = ConfigurationDiff.getNativeDiff(file.getDocument(), unfilteredDoc, file);
                            }
                            
                                                        
                            outputText += "<pre>" + diff.replace(">","&gt;").replace("<", "&lt;") + "</pre>";
   
                        } catch (FileNotFoundException ex) {
                            outputText += ("<BR/>Unable to find input file for " + file.getName());                            
                        } catch (TransformerException ex) {
                            outputText +=  "<BR/>Unable to transform " + file.getName();                            
                        } catch (ImpossibleConfigurationException ex) {
                            outputText += ("<BR/>Impossible fault in " + file.getName() + " ( " + ex.toString() + ")");                            
                        }                                                

                }
                outputText += "</html>";

                
                count++;
                
                jEditorPane1.setText(outputText);

                if (maxFaults > -1) {
                    sizeLabel.setText("Fault " + count + " of " + maxFaults);
                } else {
                    sizeLabel.setText("Fault number " + count);
                }
                
            }
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed
     

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private conferr.FaultInjectionPlan faultInjectionPlan1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JEditorPane jEditorPane1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton nativeOutput;
    private javax.swing.JLabel sizeLabel;
    private javax.swing.JRadioButton xmlOutput;
    // End of variables declaration//GEN-END:variables
    
}
